package com.fenghongzhang.sample.listview

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.fenghongzhang.sample.Food
import kotlinx.android.synthetic.main.list_view_layout.view.*

class FoodListViewAdapter(context: Context, private val resource: Int, objects: List<Food>) :ArrayAdapter<Food>(
    context,
    resource,
    objects
) {
    inner class ViewHolder(val imageView: ImageView,val textView: TextView)

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        val view:View
        val viewholder:ViewHolder
        if(convertView == null){
            view = LayoutInflater.from(context).inflate(resource,parent,false)
            val pic = view.image
            val name = view.name
            viewholder = ViewHolder(pic,name)
            view.tag =viewholder
        }else{
            view = convertView
            viewholder = view.tag as ViewHolder
        }

        //系统提供的方法getItem
        val food = getItem(position)

        // ?.是如果不为空,就执行后面的 方法
        viewholder.textView.text = food?.name
        //.let 是统一 判断不为空,才执行大括号内的方法.it是关键字
        food?.pic?.let { viewholder.imageView.setImageResource(it) }


        return view

    }

}